<template>
  <main-content title="页面列表">
    <template #search-bar>
      <search-bar inline>
        <template #normal>
          <el-form-item label="输入搜索">
            <el-input
              v-model="searchForm.name"
              placeholder="页面名称"
            />
          </el-form-item>
          <!-- <ins-cascader-filter @change="(value) => searchForm.queryInsIds = value"></ins-cascader-filter> -->
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button
              type="primary"
              @click="onsearch"
            >
              查询
            </el-button>
            <el-button
              v-has="['160101']"
              type="primary"
              @click="addPage"
            >
              新增页面
            </el-button>
          </el-form-item>
        </template>
      </search-bar>
    </template>

    <layout-table
      ref="pageListTableRef"
      url="/merchant/page/getPager"
      :param="searchForm"
    >
      <el-table-column
        label="页面名称"
        prop="name"
      />
      <el-table-column
        label="更新时间"
        prop="updateTime"
        width="180"
      >
        <template #default="scope">
          {{ formatTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="页面链接"
        prop="pageLink"
      />
      <el-table-column
        label="操作"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            v-has="['160102']"
            link
            type="primary"
            @click="editPage(scope.row.id)"
          >
            修改
          </el-button>
          <el-button
            v-has="['160103']"
            link
            type="danger"
            @click="_deletePage(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </layout-table>
  </main-content>
  <el-dialog
    v-model="dialogFormVisible"
    class="dialog-form"
    :title="title"
    width="800px"
    :before-close="resetForm"
    :close-on-click-modal="false"
  >
    <el-form
      ref="manageForm"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item
        label="页面名称"
        prop="name"
      >
        <el-input
          v-model="form.name"
          autocomplete="off"
          placeholder="页面名称"
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="跳转链接"
        prop="url"
      >
        <div class="url-form-item">
          <div
            v-if="form.url"
            class="echo-url"
          >
            {{ form.url }}
          </div>
          <el-button @click="addHref">
            添加链接
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <div>
      <el-button
        type="primary"
        @click="appendLimit"
      >
        添加限制条件
      </el-button>
      <div
        v-for="(item, index) in form.pageLinkLimits"
        class="gray"
      >
        <el-input
          v-model="item.url"
          autocomplete="off"
          placeholder="请输入http或https开头的跳转链接"
          maxlength="200"
          show-word-limit
        >
          <template #prepend>
            跳转链接：
          </template>
        </el-input>
        <Limits
          v-model="item.original"
          :options="setLimitCompontentList([
            'timeLimit',
            'groupLimit',
            'tagLimit',
            'activityLimit',
            'vipLimit',
            'ipStrategyLimit',
            'phoneStrategyLimit',
            'userInsLimit'
          ])"
        />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm()">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm(manageForm)"
        >保存</el-button>
      </span>
    </template>
  </el-dialog>

  <href-selector
    v-model:show="hrefVisible"
    :model-value="linkModel"
    :disable-tab="['mallProduct', 'mallPage']"
    @confirm="confirmHref"
  />
</template>
<script lang="ts">
export default {
  name: 'MiddlePage'
}
</script>
<script setup lang="ts">
import Limits from "@/components/limits/Index.vue";
import { deletePage } from "@/api/pointsMall";
import { storePageEdit, getStorePage } from "@/api/actapp";
import LayoutTable from "@/components/table/LayoutTable.vue";
import type { FormInstance } from "element-plus";
import moment from "moment";
import { ElMessage, ElMessageBox } from "element-plus";
import { setLimitCompontentList } from "@/utils/index";
import { ILink } from "@/components/hrefSelector/types";
import HrefSelector from "@/components/hrefSelector/HrefSelector.vue";

const pageListTableRef = ref<InstanceType<typeof LayoutTable> | null>(null)
const searchForm = reactive({
  name: '',
  type: 3,
  insId: '',
})
let form = ref({
  id: '',
  type: 3,
  name: "",
  urlType: 'link',
  url: '',
  pageLinkLimits: [] as Array<any>
});
const title = ref();
const dialogFormVisible = ref(false);
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入页面名称",
      trigger: "blur",
    },
  ],
  url: [
    {
      required: true,
      message: "请输入跳转链接",
      trigger: "blur",
    },
  ],
});
let edit = ref(false);
const manageForm = ref<FormInstance>();
const addPage = () => {
  title.value = "新建中间页";
  edit.value = false;
  dialogFormVisible.value = true;
};
const appendLimit = () => {
  form.value.pageLinkLimits.push({
    url: '',
    original: {}
  })
}
const resetForm = () => {
  form.value = {
    id: '',
    name: '',
    type: 3,
    urlType: 'link',
    url: '',
    pageLinkLimits: []
  };
  manageForm.value?.resetFields();
  dialogFormVisible.value = false;
};
const submitForm = (formEl: FormInstance | undefined) => {
  console.log(form.value.pageLinkLimits)
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const params = {
        id: edit.value == true ? form.value.id : '',
        name: form.value.name,
        type: 3,
        pageConfig: JSON.stringify({
          urlType: 'link',
          url: form.value.url,
        }),
        pageLinkLimits: []
      }
      for (let i = 0; i < form.value.pageLinkLimits.length; i++) {
        params.pageLinkLimits.push({
          url: form.value.pageLinkLimits[i].url,
          original: JSON.stringify(form.value.pageLinkLimits[i].original)
        })
      }
      const rs = await storePageEdit(params);
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: edit.value == true ? "编辑成功" : "新建成功",
        });
        resetForm();
        await pageListTableRef.value?.research()
      }
    } else {
      console.log("报错啦！请重新使一下", fields);
    }
  });
};
const editPage = async (id: number) => {
  edit.value = true;
  title.value = "编辑中间页";
  const rs = await getStorePage({ id: id });
  if (rs.code == 200) {
    let params = []
    rs.payload.pageLinkLimits.forEach(ele => {
      params.push({
        url: ele.url,
        original: JSON.parse(ele.original)
      })
    });
    form.value = {
      id: rs.payload.id,
      name: rs.payload.name,
      type: 3,
      urlType: 'manual',
      url: JSON.parse(rs.payload.pageConfig).url,
      pageLinkLimits: params
    };
    dialogFormVisible.value = true;
  }
}
const _deletePage = async (row: any) => {

  ElMessageBox.confirm("确认删除吗？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs = await deletePage({ ids: [ row.id ], names: [ row.name ] })

      if (rs.code === 200) {
        ElMessage.success('删除成功')
        await pageListTableRef.value?.research()
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
}
const formatTime = (val: number) => {
  return moment(val).format('YYYY-MM-DD HH:mm:ss')
}

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    // 待完善
    searchForm.insId = insId.value
  },
  {
    deep: true
  }
)

const hrefVisible = ref(false);
const linkModel = ref({
  urlType: "manual",
  url: "",
});
const addHref = () => {
  linkModel.value.url = form.value.url;
  hrefVisible.value = true;
}
const confirmHref = (link: ILink) => {
  linkModel.value = link
  form.value.url = link.url
}

//查询按钮查询
const onsearch = async () => {
  await pageListTableRef.value?.research()
};

</script>

<style lang="scss" scoped>
.gray {
  margin: 10px auto;
  width: 80%;
  padding: 20px;
  box-sizing: border-box;
  background-color: #F4F5F9;
}

.url-form-item {
  flex: 1;
  display: flex;
  align-items: center;

  .echo-url {
    width: 461px;
    margin-right: 10px;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: keep-all;
    white-space: nowrap;
  }
}
</style>
